package com.mh.pojo;

import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;
import java.util.Map;

/**
 * Date:2023/4/23
 * author:zmh
 * description: WebSocket-用户管理员
 **/


public class UserManager {
    private static volatile UserManager instance;

    private UserManager() {
        // private constructor
    }

    public static UserManager getInstance() {
        if (instance == null) {
            synchronized (UserManager.class) {
                if (instance == null) {
                    instance = new UserManager();
                }
            }
        }
        return instance;
    }

    private HashMap<WebSocketSession, User> userMap = new HashMap<>();

    public void add(WebSocketSession id, User user) {
        if(!hasKey(id)) {
            userMap.put(id, user);
        }else{
            System.out.print("用户已存在... 存在的id为"+ id);
        }
    }

    public User get(WebSocketSession id) {
        return userMap.get(id);
    }
    public WebSocketSession getSessionByUserName(String userName) {
        return userMap.entrySet().stream()
                .filter(entry -> entry.getValue().getUserName().equals(userName))
                .map(Map.Entry::getKey)
                .findFirst()
                .orElse(null);
    }

    public boolean hasKey(WebSocketSession id) {

        for (WebSocketSession item : userMap.keySet()){
            if(item.getId() == id.getId()) return true;
        }
        return false;
//        return userMap.containsKey(id);
    }

    public HashMap<WebSocketSession, User> getUserMapCopy() {
        HashMap<WebSocketSession, User> copy = new HashMap<>();
        for (Map.Entry<WebSocketSession, User> entry : userMap.entrySet()) {
            WebSocketSession key = entry.getKey();
            User value = entry.getValue();
            copy.put(key, value); // assuming User class has a copy constructor
        }
        return copy;
    }
}
